const {
  RoleNotFoundError,
  RoleHasMenuBindingError,
  RoleHasUserBindingError,
} = require('../../domain/role/error')
const Usecase = require('../../shared/usecase/Usecase')

class DeleteRole extends Usecase {
  constructor({ roleRepo, database, currentUser }) {
    super(['DeletedRole'])
    this.roleRepo = roleRepo
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }

  async execute(data) {
    const { DeletedRole } = this.eventMap
    const role = await this.roleRepo.findById(data, {
      include: ['menuList', 'userList'],
    })

    if (!role) throw new RoleNotFoundError(data)
    if (role.hasMenu()) throw new RoleHasMenuBindingError(role.name)
    if (role.hasUser()) throw new RoleHasUserBindingError(role.name)

    const transaction = await this.sequelize.transaction()
    try {
      await this.roleRepo.remove(role, { transaction })
      await transaction.commit()
      this.emit(DeletedRole, role)
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = DeleteRole
